<template>
    <el-input v-click-out="handlerChangeStatus" autofocus ref="inputRef" v-model="inputVal" size="small" class="input" @click="handlerSelectInput" v-show="editing" />
    <div @dblclick="handlerEdit" @keydown="handleKeyDown" :class="selected ? 'active' : ''" class="tag" @click="handlerSelect" v-if="!editing">
        {{ content }}
    </div>
</template>
<script setup>
import { ref, watch } from 'vue';

const emit = defineEmits(['select', 'remove']);

const props = defineProps({
    selected: {
        type: Boolean,
        default: false,
    },
    content: {
        type: String,
        default: '',
    },
});

const editing = ref(false);
const inputVal = ref(props.content);
const inputRef = ref();

const handleRemove = () => {
    emit('remove');
};

const handlerSelect = (e) => {
    e.stopPropagation();
    emit('select');
};

const handlerEdit = () => {
    editing.value = true;
    if (inputRef.value) {
        inputRef.value.focus();
    }
};

const handleKeyDown = (e) => {
  // 监听退格键
  if (e.key === 'Backspace' || e.keyCode === 8) {
    if (inputVal.value) {
        editing.value = false;
    }
  }
};

const handlerSelectInput = (e) => {
    e.stopPropagation(); // 阻止事件冒泡
};

watch(() => props.selected, (newVal, oldVal) => {
    if (newVal !== oldVal && !newVal) {
        editing.value = false;
    }
});

const handlerChangeStatus = () => {
    editing.value = false;
};

</script>
<style scoped lang="scss">
.tag {
    cursor: pointer;
    background-color: #d7e6f8;
    padding: 0 5px;
}

.active {
    color: #fff;
    background-color: #3B7AEE;
}

.input {
    width: auto;
    :deep(.el-input__wrapper) {
        box-shadow: none;
    }
}
</style>